/*
 * Copyright (c) 2023, LXMS (lxinet.cn).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lxinet.lxms.framework.security.filter;

import cn.lxinet.lxms.framework.core.message.CommonErrorCode;
import cn.lxinet.lxms.framework.core.utils.StringUtils;
import cn.lxinet.lxms.framework.core.vo.Result;
import cn.lxinet.lxms.framework.security.config.JwtConfig;
import cn.lxinet.lxms.framework.security.entity.LxmsUser;
import cn.lxinet.lxms.framework.security.service.LxmsUserDetailService;
import com.auth0.jwt.exceptions.TokenExpiredException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * jwt身份验证过滤器
 *
 * @author zcx
 * @date 2023/07/19
 */
@Slf4j
@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private LxmsUserDetailService lxmsUserDetailService;
    public static List<RequestMatcher> permissMatchers = new ArrayList<>();
    static {
        permissMatchers.add(new AntPathRequestMatcher("/system/auth/login"));
        permissMatchers.add(new AntPathRequestMatcher("/system/getPublicKey"));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(JwtConfig.HEADER);
        try {
            if (!this.requireAuthentication(request)) {
                filterChain.doFilter(request, response);
                return;
            }
            if (StringUtils.isNotBlank(token)){
                token = token.replace("Bearer ", "");
            }
            LxmsUser lxmsUser = jwtConfig.getUser(token);
            if (lxmsUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                lxmsUser = lxmsUserDetailService.loadUserByUsername(lxmsUser.getUsername());
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(lxmsUser, token, lxmsUser.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
            filterChain. doFilter(request, response);
        }catch (TokenExpiredException e){
            Result.responseJson(response, CommonErrorCode.AUTHORIZATION_EXPIRED);
        }catch (Exception e){
            log.error("系统异常", e);
            Result.responseJson(response, CommonErrorCode.SYSTEM_EXCEPTION);
        }
    }

    private boolean requireAuthentication(HttpServletRequest request) {
        String authHeader = request.getHeader(JwtConfig.HEADER);
        if  (authHeader == null) {
            return false;
        }
        for (RequestMatcher requestMatcher : permissMatchers){
            boolean isPermissiveUrl = requestMatcher.matches(request);
            if (isPermissiveUrl) {
                return false;
            }
        }
        return true;
    }
}
